I am trying to make a program which will return the number of words in a given sentence. It should be able to give correct information even if there are multiple spaces before the sentence, between words or after the sentence. I haven't been able to make it handle multiple spaces after the sentence, because it will always give me the number of words +1.
I thought this could be because it was passing the \0 in the end of the string, so I tried to fill all the empty slots in the string with \0.
I would appreciate if you could help me understand what I am doing wrong!
The program goes as follow:
Code:
#include <stdio.h>
void stuff(char s[], int n){
int i = 0;
while (s[i] != '\0'){
i++;
}
for ( i; i < n; i++){
s[i] = '\0';
}
}
// A function to count words:
int wcount( char s[] ){
int i = 0;
int num = 1;
while ( s[i] == ' ' ){
i++; // Preventing errors in case of multiple spaces before the sentence.
}
while ( s[i] != '\0' ){
if ( s[i] == ' '){
num++;
while ( s[i] == ' ' ){
i++; // Preventing errors if there are multiple spaces between words.
}
}
i++;
}
return( num );
}
void main(){
int const DIM = 100;
char str[DIM];
gets(str);
stuff(str, DIM);
printf( "The sentence has %d words \n", wcount(str) );
}
Thank you very much in advance!